#include "sgm51242r8_driver.h"

void Inf_SGM51242R8_Device2Receive(SPI_HandleTypeDef *hspix, uint16_t *data)
{
    HAL_StatusTypeDef status;

    SPI2_CS_Enable();
    status = HAL_SPI_Receive(hspix, (uint8_t *)data, 1, 100);
    if (status != HAL_OK)
    {
        printf("receive fail, error code:%d\n", status);
    }
    SPI2_CS_Disable();
    
}

void Inf_SGM51242R8_Device1Receive(SPI_HandleTypeDef *hspix, uint16_t *data)
{
    SPI1_CS_Enable();
    HAL_SPI_Receive(hspix, (uint8_t *)data, 1, 100);
    SPI1_CS_Disable();
}

void Inf_SGM51242R8_SendData(SPI_HandleTypeDef *hspix, uint16_t *data)
{
    HAL_StatusTypeDef status;
    SPI1_CS_Enable();
    SPI2_CS_Enable();
    status = HAL_SPI_Transmit(hspix, (uint8_t *)data, 1, 100);
    SPI2_CS_Disable();
    SPI1_CS_Disable();
    if (status != HAL_OK)
    {
        printf("send fail, error code:%d\n", status);
    }
}

void Inf_SGM51242R8_ReadBack(SPI_HandleTypeDef *hspix)
{
    uint16_t result = 0;
    uint16_t adc_seq[1] = {0x3848};
    uint16_t adc_ctrl[1] = {0x384C};
    uint16_t reset[1] = {0x387C};
    uint16_t config[1] = {0x3810};
    Inf_SGM51242R8_SendData(hspix, adc_seq);
    HAL_Delay(1);
    Inf_SGM51242R8_Device1Receive(hspix, &result);
    // if (result != 0x02FF)
    // {
    //     printf("Config ADC_Sequence Fail\n");
    // }
    printf("sequence : %04X   ", result);
    HAL_Delay(1);
    Inf_SGM51242R8_SendData(hspix, adc_ctrl);
    HAL_Delay(1);
    Inf_SGM51242R8_Device1Receive(hspix, &result);
    // if (result != 0x0220)
    // {
    //     printf("Config ADC_Control Fail\n");
    // }
    printf("control : %04X\n", result);
}

void Inf_SGM51242R8_Init(SPI_HandleTypeDef *hspix)
{
    uint16_t reset[1] = {0x7DAC};
    uint16_t sequence[1] = {0x12FF};
    uint16_t configer[1] = {0x20FF};
    uint16_t control[1] = {0x1820};
    uint16_t power_up[1] = {0x5A00};
    uint16_t ban[1] = {0x3000};

    HAL_Delay(100);
    Inf_SGM51242R8_SendData(hspix, reset);
    HAL_Delay(10);
    Inf_SGM51242R8_SendData(hspix, ban);
    HAL_Delay(10);
    Inf_SGM51242R8_SendData(hspix, control);
    HAL_Delay(10);
    Inf_SGM51242R8_SendData(hspix, configer);
    HAL_Delay(10);
    Inf_SGM51242R8_SendData(hspix, power_up);
    HAL_Delay(10);
    // 必须最后一个
    Inf_SGM51242R8_SendData(hspix, sequence);
    HAL_Delay(10);

    Inf_SGM51242R8_ReadBack(hspix);

}
